package com.biao.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.biao.auth.feign.MemberFeignService;
import com.biao.auth.feign.ThirdPartFeignService;
import com.biao.auth.vo.UserLoginVo;
import com.biao.auth.vo.UserRegistVo;
import com.biao.common.constant.AuthServerConstant;
import com.biao.common.utils.R;
import com.biao.common.vo.MemberRespVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.biao.common.constant.AuthServerConstant.LOGIN_USER;
import static com.biao.common.constant.AuthServerConstant.SMS_CODE_CACHE_PREFIX;
import static com.biao.common.exception.BizCodeEnume.SMS_CODE_EXCEPTION;

@Controller
public class LoginController {

    @Autowired
    private ThirdPartFeignService thirdPartFeignService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private MemberFeignService memberFeignService;


    @GetMapping("/login.html")
    public String loginPage(HttpSession session) {
        if (session.getAttribute(LOGIN_USER)==null) {
            return "login";
        }
        return "redirect:http://mall.com";
    }

    //验证码请求 实际上是email
    @ResponseBody
    @GetMapping("/sms/sendCode")
    public R sendCode(@RequestParam("phone") String phone) {

        //接口防刷
        String redisCode = redisTemplate.opsForValue().get(SMS_CODE_CACHE_PREFIX + phone);
        if (StringUtils.isNotBlank(redisCode)) {
            Long current = Long.parseLong(redisCode.split("_")[1]);
            if (System.currentTimeMillis() - current < 60000) {
                return R.error(SMS_CODE_EXCEPTION.getCode(), SMS_CODE_EXCEPTION.getMsg());
            }
        }
        long l = System.currentTimeMillis();
        String code = "1234_" + l;
        thirdPartFeignService.sendCode(phone, code.split("_")[0]);
        redisTemplate.opsForValue().set(SMS_CODE_CACHE_PREFIX + phone, code, 5, TimeUnit.MINUTES);
        return R.ok();
    }

    @PostMapping("/regist")
    public String regist(@Valid UserRegistVo vo, BindingResult result, RedirectAttributes redirectAttributes) {
        if (result.hasErrors()) {//校验出错
            Map<String, String> errors = result.getFieldErrors().stream()
                    .collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            redirectAttributes.addFlashAttribute("errors", errors);
            //如果校验出错,重定向到注册页(转发会重复提交表单)
            return "redirect:http://auth.mall.com/reg.html";
        }

        //注册
        String redisCode = redisTemplate.opsForValue().get(SMS_CODE_CACHE_PREFIX + vo.getPhone());
        if (StringUtils.isNotBlank(redisCode)) {
            String code = redisCode.split("_")[0];
            if (!Objects.equals(code, vo.getCode())) {
                Map<String, String> errors = new HashMap<>();
                errors.put("code", "验证码错误");
                redirectAttributes.addFlashAttribute("errors", errors);
                return "redirect:http://auth.gulimall.com/reg.html";
            }

        } else {
            Map<String, String> errors = new HashMap<>();
            errors.put("code", "验证码过期");
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.mall.com/reg.html";
        }
        //验证码通过
        redisTemplate.delete(SMS_CODE_CACHE_PREFIX + vo.getPhone());
        R r = memberFeignService.regist(vo);
        if (r.getCode() == 0) {//成功
            return "redirect:http://auth.mall.com/login.html";
        } else {
            Map<String, String> errors = new HashMap<>();

            errors.put("msg", (String) r.get("msg"));
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.mall.com/reg.html";
        }
    }

    @PostMapping("/login")
    public String login(@Valid UserLoginVo vo, BindingResult result, RedirectAttributes redirectAttributes, HttpSession session) {
        if (result.hasErrors()) {
            Map<String, String> errors = new HashMap<>();
            errors.put("msg", "账号或密码不能为空");
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.mall.com/login.html";
        }
        R r = memberFeignService.login(vo);
        if (r.getCode() == 0) {
            MemberRespVo memberRespVo = r.getData(new TypeReference<MemberRespVo>() {
            });
            session.setAttribute(AuthServerConstant.LOGIN_USER, memberRespVo);
            return "redirect:http://mall.com";
        } else {
            Map<String, String> errors = new HashMap<>();
            errors.put("msg", (String) r.get("msg"));
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.mall.com/login.html";
        }

    }
}

